<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\BasePostLabelsModel;
use app\model\PostLabelsModel;
use think\App;

class PostLabels extends Base {

    protected $middleware = [Auth::class];

    private $model;

    private $req;

    private $aid;

    private $page;

    private $limit;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->model = new BasePostLabelsModel();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 10;

        $this->aid = $this->isLogin();
    }



    public function getList(){

        $where=[];

        $where[] = ["is_delete","=",0];

        $list = $this->model->getList($where,$this->page,$this->limit,["update_at"=>"DESC"]);

        $total = $this->model->getTotal($where);

        return $this->succData($total,$list);

    }

    /*
     * 获取店铺列表
     * */
    public function getInfo(){

        if(!isset($this->req['post_id']) || empty($this->req['post_id'])){
            return $this->fail("帖子Id 不能为空");
        }

        $info = $this->model->getInfo($this->req['post_id']);

        return $this->succ($info);

    }





    //新增
    public function add(){

        if(!$this->req["label_name"]){
            return $this->fail("标签名不能为空");
        }

        if($this->model->getTotal(["label_name"=>$this->req["label_name"]]) > 0){
            return $this->fail("该标签名已经存在");
        }

        $res = $this->model->addOne(["label_name"=>$this->req["label_name"]]);

        if($res){
            return $this->succ("新增成功");
        }else{
            return $this->fail("新增失败");
        }
    }


    public function edit(){

        if(!$this->req["base_post_label_id"]){
            return $this->fail("请选择要操作的标签");
        }

        if(!$this->req["label_name"]){
            return $this->fail("标签名不能为空");
        }

        $where =[] ;
        $where[] = ["label_name","=",$this->req["label_name"]];
        $where[] = ["base_post_label_id","<>",$this->req["base_post_label_id"]];
        if($this->model->getTotal($where) > 0){
            return $this->fail("该标签名已经存在");
        }

        $res = $this->model->updateOne($this->req["base_post_label_id"],["label_name"=>$this->req["label_name"]]);

        if($res){
            $this->model->delCache($this->req["base_post_label_id"]);
            return $this->succ("修改成功");
        }else{
            return $this->fail("修改失败");
        }
    }


    public function del(){

        if(!$this->req["base_post_label_id"]){
            return $this->fail("请选择要操作的标签");
        }

        $res = $this->model->where("base_post_label_id",'=',$this->req["base_post_label_id"])->delete();

        if($res){
            return $this->succ("删除成功");
        }else{
            return $this->fail("删除失败");
        }
    }

}
